package com.tqjc.business.interactivewithscan.entity;

import com.tqjc.business.interactivewithscan.exception.CustomException;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.net.NetClient;
import io.vertx.core.net.NetClientOptions;
import io.vertx.core.net.NetSocket;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ArrayBlockingQueue;

/**
 * @program: C20005_Xianggang_new
 * @description: 设备Socket连接基础类，使用Vertx实现
 * @author: Patienyon
 * @create: 2023-11-01 18:50
 **/
@Slf4j
public class DeviceSocketClient extends AbstractVerticle {
    @Getter
    private ScanDeviceData device;


    public DeviceSocketClient(ScanDeviceData device) {
        this.device = device;
    }

    @Getter
    private NetSocket socket;

    private boolean succeeded;
    private ArrayBlockingQueue queue;

    public DeviceSocketClient(ScanDeviceData device, ArrayBlockingQueue queue) {
        this.device = device;
        this.queue = queue;
    }

    @Override
    public void start() throws Exception {
        if (device == null) {
            return;
        }

        NetClientOptions options = new NetClientOptions();
        options.setReceiveBufferSize(10000000);
        NetClient client = vertx.createNetClient(options);
        client.connect(device.getPort(), device.getHost(), r -> {
            this.succeeded = r.succeeded();
            if (r.succeeded()) {
                log.info("设备：【" + device.getDeviceName() + "】已经成功连接！");
                NetSocket socket = r.result();
                this.socket = socket;
                socket.closeHandler(close -> {
                    try {
                        this.stop();
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        log.error("设备：【" + device.getDeviceName() + "】已经断开连接！");
                        succeeded = false;
                        throw new CustomException(-1, "设备：【" + device.getDeviceName() + "】已经断开连接！");
                    }
                });
            }
            queue.offer(succeeded);
        });
    }

    public boolean succeeded() {
        return succeeded;
    }

}
